#include "Chat.h"

#include "MessageListener.h"

#include <packet/Message.h>
#include <ChatManager.h>


Chat::Chat(ChatManager * chatManager, std::string participant, std::string threadID) : 
	chatManager(chatManager),
	participant(participant),
	threadID(threadID) 
{
}

void Chat::sendMessage(std::string & text) {
    Message * message = new Message(participant, Message::CHAT);
    message->setThread(threadID);
    message->setBody(text);
    chatManager->sendMessage(this, message);
}

void Chat::addMessageListener(MessageListener * listener) {
    if(listener) {
		listeners.push_back(listener);
    }
}

void Chat::removeMessageListener(MessageListener * listener) {
	//delete listener;
    listeners.remove(listener);
}

std::list<MessageListener*> Chat::getListeners() {
    return listeners;
}

PacketCollector * Chat::createCollector() {
    return chatManager->createPacketCollector(this);
}

void Chat::deliver(Message * message) {
    // Because the collector and listeners are expecting a thread ID with
    // a specific value, set the thread ID on the message even though it
    // probably never had one.
    message->setThread(threadID);

    for (std::list<MessageListener*>::iterator it = listeners.begin(); it != listeners.end(); ++it) {
        (*it)->processMessage(this, message);
    }
}

bool Chat::operator==( const Chat & chat) const
{
	return threadID == chat.getThreadID() && participant == chat.getParticipant();
}
